/**
 * cursorActions.js - Cursor核心功能模块
 * 
 * 提供核心方法：
 * 1. executeRenewal - 一键续杯
 * 2. activatePrivilege - 一键特权
 * 3. getActivationRules - 获取激活规则（远程）
 * 4. getCursorAppRoot - 获取Cursor安装路径
 * 5. getCursorVersion - 获取Cursor版本号
 * 6. getOrCreateUUID - 获取或创建设备UUID
 * 
 * 特点：
 * - 纯函数，无UI依赖
 * - 移除不必要的提示信息
 * - 保留关键错误信息
 * - 支持自动检测Cursor安装路径
 * 
 * 使用示例：
 * 
 * const { 
 *   executeRenewal, 
 *   activatePrivilege, 
 *   getActivationRules,
 *   getCursorAppRoot,
 *   getCursorVersion,
 *   getOrCreateUUID
 * } = require('./cursorActions');
 * 
 * // 超级简化调用（推荐）- 所有参数自动获取
 * const cardCode = "MBHVIP-1234-5678-9012";
 * 
 * // 1. 获取激活规则（自动检测路径、版本、UUID）
 * const rules = await getActivationRules(cardCode);
 * 
 * // 2. 一键特权（自动检测路径）
 * if (rules) {
 *   const result = await activatePrivilege(rules);
 *   console.log(result);
 * }
 * 
 * // 3. 一键续杯
 * const renewalResult = await executeRenewal({
 *   token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
 * });
 * 
 * // 查看自动检测的信息（可选）
 * const appRoot = getCursorAppRoot();
 * const cursorVersion = getCursorVersion();
 * const uuid = getOrCreateUUID();
 * console.log('路径:', appRoot, '版本:', cursorVersion, 'UUID:', uuid);
 */

const fs = require('fs');
const os = require('os');
const path = require('path');
const https = require('https');
const http = require('http');
const crypto = require('crypto');

// ============= 配置常量 =============

const API_ENDPOINTS = [
  'https://manbeihu.top',
  'https://ggs108.top',
  'http://143.14.122.22',
  'https://starriver.icu'
];

// ============= 辅助工具函数 =============

/**
 * 安全解密响应数据
 */
function secureDecryptResponse(responseData, cardCode) {
  try {
    if (!responseData || typeof responseData !== 'object' || !responseData.encrypted) {
      return responseData;
    }
    
    const { encrypted, window, signature } = responseData;
    const encKey = 'enc_manbeihu_v2025_3h8f5r9t2v7c4x';
    
    const cardHash = crypto.createHash('sha256').update(cardCode).digest('hex').substr(0, 16);
    const combinedHash = crypto.createHash('sha256').update(cardCode + window + encKey).digest('hex');
    const finalKey = crypto.createHash('sha256').update(combinedHash + cardHash).digest('hex');
    
    const computedSignature = crypto.createHmac('sha256', Buffer.from(finalKey, 'hex'))
      .update(encrypted)
      .digest('hex');
    
    if (computedSignature !== signature) {
      return responseData;
    }
    
    const encryptedBuffer = Buffer.from(encrypted, 'base64');
    const iv = encryptedBuffer.slice(0, 16);
    const ciphertext = encryptedBuffer.slice(16);
    
    const decipher = crypto.createDecipheriv('aes-256-cbc', Buffer.from(finalKey, 'hex'), iv);
    let decrypted = decipher.update(ciphertext);
    decrypted = Buffer.concat([decrypted, decipher.final()]);
    
    const decryptedData = JSON.parse(decrypted.toString());
    
    const cardHashCheck = crypto.createHash('md5').update(cardCode).digest('hex').substr(0, 8);
    if (decryptedData.card_hash !== cardHashCheck) {
      return responseData;
    }
    
    return decryptedData.payload;
  } catch (error) {
    return responseData;
  }
}

/**
 * 发起HTTP/HTTPS请求
 */
function makeRequest(url, options, postData, isHttps = true) {
  return new Promise((resolve, reject) => {
    const protocol = isHttps ? https : http;
    const req = protocol.request(url, options, (res) => {
      let data = '';
      res.on('data', (chunk) => data += chunk);
      res.on('end', () => {
        if (res.statusCode >= 200 && res.statusCode < 300) {
          resolve(data);
        } else {
          reject(new Error(`HTTP ${res.statusCode}: ${data}`));
        }
      });
    });
    
    req.on('error', (error) => {
      reject(error);
    });
    
    req.setTimeout(30000);
    
    if (postData) {
      req.write(postData);
    }
    
    req.end();
  });
}

/**
 * 快速健康检查，找到最快的API端点
 */
function quickHealthCheck() {
  return new Promise((resolve) => {
    let fastest = null;
    let completed = 0;
    const controllers = [];
    
    API_ENDPOINTS.forEach((endpoint, index) => {
      const controller = new AbortController();
      controllers.push(controller);
      
      const startTime = Date.now();
      const isHttps = endpoint.startsWith('https://');
      const protocol = isHttps ? https : http;
      
      const req = protocol.request({
        method: 'GET',
        timeout: 1000,
        signal: controller.signal
      }, (res) => {
        const latency = Date.now() - startTime;
        
        if (!fastest || latency < fastest.latency) {
          fastest = { url: endpoint, latency };
          
          // 取消其他请求
          controllers.forEach((ctrl, i) => {
            if (i !== index) {
              try { ctrl.abort(); } catch (e) {}
            }
          });
          
          resolve(fastest);
        }
      });
      
      req.on('error', () => {
        completed++;
        if (completed === API_ENDPOINTS.length && !fastest) {
          resolve(API_ENDPOINTS[0] ? { url: API_ENDPOINTS[0], latency: 9999 } : null);
        }
      });
      
      req.end();
    });
    
    // 超时保护
    setTimeout(() => {
      if (!fastest) {
        resolve(API_ENDPOINTS[0] ? { url: API_ENDPOINTS[0], latency: 9999 } : null);
      }
    }, 1500);
  });
}

/**
 * 带故障转移的HTTP请求
 */
async function makeHttpsRequestWithFallback(path, options, postData) {
  // 先进行健康检查
  const fastestEndpoint = await quickHealthCheck();
  
  if (fastestEndpoint) {
    try {
      const isHttps = fastestEndpoint.url.startsWith('https://');
      const result = await makeRequest(`${fastestEndpoint.url}${path}`, options, postData, isHttps);
      return result;
    } catch (error) {
      console.error('最快端点请求失败，尝试其他端点...');
    }
  }
  
  // 依次尝试所有端点
  let lastError = null;
  for (const endpoint of API_ENDPOINTS) {
    if (fastestEndpoint && endpoint === fastestEndpoint.url) {
      continue;
    }
    
    try {
      const isHttps = endpoint.startsWith('https://');
      const result = await makeRequest(`${endpoint}${path}`, options, postData, isHttps);
      return result;
    } catch (error) {
      lastError = error;
    }
  }
  
  throw lastError || new Error('所有API端点都无法访问');
}

/**
 * 生成随机CS值
 * CS值格式: 64位十六进制/64位十六进制
 */
function generateRandomCS() {
  try {
    const generateHex = (length) => {
      return Array.from({ length }, () => 
        Math.floor(Math.random() * 256)
          .toString(16)
          .padStart(2, '0')
      ).join('');
    };
    
    const part1 = generateHex(32); // 32字节 = 64位十六进制
    const part2 = generateHex(32);
    
    return `${part1}/${part2}`;
  } catch (error) {
    console.error('生成CS值失败:', error);
    return '9e152b505686b794dbdf6f26fca1ce77d96a3b141d49b07a7f502e431cfe438c/b7f838ec6ac433905755c60cfa9205991d0d42fda82b7431553aa56ccdc050d4';
  }
}

/**
 * 获取 .cursor_info 文件路径
 */
function getCursorInfoPath() {
  const homeDir = os.homedir();
  return path.join(homeDir, '.cursor_info');
}

/**
 * 检查 .cursor_info 文件是否存在
 */
function cursorInfoExists() {
  const filePath = getCursorInfoPath();
  return fs.existsSync(filePath);
}

/**
 * 创建 .cursor_info 文件
 */
function createCursorInfoFileInternal() {
  try {
    const filePath = getCursorInfoPath();
    
    if (cursorInfoExists()) {
      return true;
    }
    
    const randomCS = generateRandomCS();
    const initialContent = `token:""\ncs:"${randomCS}"`;
    
    fs.writeFileSync(filePath, initialContent, 'utf-8');
    return true;
  } catch (error) {
    console.error('创建.cursor_info文件失败:', error);
    return false;
  }
}

/**
 * 写入Token到 .cursor_info 文件
 */
function writeTokenToCursorInfoInternal(token) {
  try {
    if (!token) {
      console.error('Token为空，无法写入');
      return false;
    }
    
    const filePath = getCursorInfoPath();
    const randomCS = generateRandomCS();
    const content = `token:"${token}"\ncs:"${randomCS}"`;
    
    fs.writeFileSync(filePath, content, 'utf-8');
    return true;
  } catch (error) {
    console.error('写入Token失败:', error);
    return false;
  }
}

/**
 * 获取Cursor关键文件路径（简化版，不依赖vscode API）
 */
function getKeyFiles(appRoot) {
  const platform = process.platform;
  let homeDir = os.homedir();
  
  // Linux特殊处理
  if (platform === 'linux' && homeDir === '/root') {
    const sudoUser = process.env.SUDO_USER;
    if (sudoUser && sudoUser !== 'root') {
      homeDir = path.join('/home', sudoUser);
    }
  }
  
  // 如果没有提供appRoot，尝试使用默认路径
  let appPath = appRoot;
  if (!appPath) {
    // 这里简化处理，实际使用时需要传入正确的appRoot
    appPath = '';
  }
  
  let resourcesPath = path.join(appPath, 'resources', 'app');
  if (!fs.existsSync(resourcesPath)) {
    resourcesPath = appPath;
  }
  
  const keyFiles = {
    distMain: path.join(resourcesPath, 'extensions', 'cursor-always-local', 'dist', 'main.js'),
    outMain: path.join(resourcesPath, 'out', 'main.js'),
    workbench: path.join(resourcesPath, 'out', 'vs', 'workbench', 'workbench.desktop.main.js'),
    extHost: path.join(resourcesPath, 'out', 'vs', 'workbench', 'api', 'node', 'extensionHostProcess.js')
  };
  
  // 检查文件是否存在
  const result = {};
  for (const [key, filePath] of Object.entries(keyFiles)) {
    if (fs.existsSync(filePath)) {
      result[key] = filePath;
    } else {
      result[key] = undefined;
    }
  }
  
  return result;
}

/**
 * 检查必需文件
 */
function checkRequiredFiles(keyFiles) {
  const result = {
    hasAnyTargetFile: !!keyFiles.distMain || !!keyFiles.outMain || !!keyFiles.workbench || !!keyFiles.extHost,
    missingFiles: [],
    availableFiles: []
  };
  
  for (const [key, filePath] of Object.entries(keyFiles)) {
    if (filePath) {
      result.availableFiles.push(key);
    } else {
      result.missingFiles.push(key);
    }
  }
  
  return result;
}

/**
 * 获取配置目录路径
 * 统一使用用户主目录下的 cursor-restore 目录
 */
function getConfigDir() {
  const homeDir = os.homedir();
  return path.join(homeDir, 'cursor-restore');
}

/**
 * 获取配置文件路径
 * 统一从用户主目录下的 cursor-restore/config.json 读取
 */
function getConfigPath(appRoot = null) {
  return path.join(getConfigDir(), 'config.json');
}

/**
 * 确保配置目录存在
 */
function ensureConfigDir(configPath) {
  const configDir = path.dirname(configPath);
  if (!fs.existsSync(configDir)) {
    fs.mkdirSync(configDir, { recursive: true });
  }
}

/**
 * 加载配置文件
 */
function loadConfig() {
  const defaultConfig = {
    card_code: '',
    token: '',
    premium_usage: 0,
    max_premium_usage: 50,
    last_updated: '',
    uuid: ''
  };
  
  const configPath = getConfigPath();
  
  // 确保配置目录存在
  ensureConfigDir(configPath);
  
  if (fs.existsSync(configPath)) {
    try {
      const content = fs.readFileSync(configPath, 'utf-8');
      const config = JSON.parse(content);
      return { ...defaultConfig, ...config };
    } catch (error) {
      console.error('加载配置文件失败:', error);
      return defaultConfig;
    }
  }
  
  return defaultConfig;
}

/**
 * 保存配置文件
 */
function saveConfig(configData) {
  try {
    const configPath = getConfigPath();
    ensureConfigDir(configPath);
    
    const currentConfig = loadConfig();
    const mergedConfig = { ...currentConfig, ...configData };
    
    const tempPath = configPath + '.tmp';
    const content = JSON.stringify(mergedConfig, null, 4);
    
    fs.writeFileSync(tempPath, content, 'utf-8');
    fs.renameSync(tempPath, configPath);
    
    return true;
  } catch (error) {
    console.error('保存配置文件失败:', error);
    return false;
  }
}

/**
 * 获取或创建UUID
 */
function getOrCreateUUID() {
  const config = loadConfig();
  
  if (config.uuid) {
    return config.uuid;
  }
  
  const newUUID = crypto.randomUUID();
  config.uuid = newUUID;
  saveConfig(config);
  
  return newUUID;
}

/**
 * 获取Cursor安装路径（appRoot）
 * 尝试自动检测Cursor的安装位置
 */
function getCursorAppRoot() {
  try {
    const platform = os.platform();
    const homeDir = os.homedir();
    const possiblePaths = [];
    
    if (platform === 'win32') {
      // Windows常见安装路径
      possiblePaths.push(
        path.join(homeDir, 'AppData', 'Local', 'Programs', 'cursor', 'resources', 'app'),
        path.join(homeDir, 'AppData', 'Local', 'Programs', 'Cursor', 'resources', 'app'),
        path.join('C:', 'Program Files', 'Cursor', 'resources', 'app'),
        path.join('C:', 'Program Files (x86)', 'Cursor', 'resources', 'app')
      );
    } else if (platform === 'darwin') {
      // macOS常见安装路径
      possiblePaths.push(
        '/Applications/Cursor.app/Contents/Resources/app',
        path.join(homeDir, 'Applications', 'Cursor.app', 'Contents', 'Resources', 'app')
      );
    } else if (platform === 'linux') {
      // Linux常见安装路径
      possiblePaths.push(
        '/usr/share/cursor/resources/app',
        '/opt/cursor/resources/app',
        path.join(homeDir, '.local', 'share', 'cursor', 'resources', 'app'),
        path.join(homeDir, 'cursor', 'resources', 'app')
      );
    }
    
    // 检查每个可能的路径
    for (const possiblePath of possiblePaths) {
      if (fs.existsSync(possiblePath)) {
        const packageJsonPath = path.join(possiblePath, 'package.json');
        if (fs.existsSync(packageJsonPath)) {
          console.log('找到Cursor安装路径:', possiblePath);
          return possiblePath;
        }
      }
    }
    
    console.error('无法自动检测Cursor安装路径');
    return null;
  } catch (error) {
    console.error('获取Cursor安装路径失败:', error);
    return null;
  }
}

/**
 * 获取Cursor版本号
 */
function getCursorVersion() {
  try {
    const appRoot = getCursorAppRoot();
    if (!appRoot) {
      console.error('无法自动检测Cursor安装路径，无法获取版本');
      return null;
    }
    
    let resourcesPath = path.join(appRoot, 'resources', 'app');
    if (!fs.existsSync(resourcesPath)) {
      resourcesPath = appRoot;
    }
    
    const packageJsonPath = path.join(resourcesPath, 'package.json');
    
    if (!fs.existsSync(packageJsonPath)) {
      console.error('package.json文件不存在:', packageJsonPath);
      return null;
    }
    
    const content = fs.readFileSync(packageJsonPath, 'utf-8');
    const packageData = JSON.parse(content);
    
    if (packageData && packageData.version) {
      return packageData.version;
    } else {
      console.error('package.json中未找到version字段');
      return null;
    }
  } catch (error) {
    console.error('读取Cursor版本失败:', error);
    return null;
  }
}

// ============= 核心方法 =============

/**
 * 获取规则缓存文件路径
 */
function getDecryptedDataPath() {
  // 统一使用用户主目录下的 cursor-restore 目录存储缓存
  return path.join(getConfigDir(), 'rules_cache.json');
}

/**
 * 读取缓存数据
 */
function loadDecryptedData(cursorVersion) {
  try {
    const dataPath = getDecryptedDataPath();
    
    if (!fs.existsSync(dataPath)) {
      return null;
    }
    
    const content = fs.readFileSync(dataPath, 'utf-8');
    const data = JSON.parse(content);
    
    // 检查是否有对应版本的缓存
    if (data && data[cursorVersion] && data[cursorVersion].data) {
      console.log(`从缓存读取数据: 版本 ${cursorVersion}`);
      return data[cursorVersion].data;
    }
    
    return null;
  } catch (error) {
    console.error('读取缓存数据失败:', error);
    return null;
  }
}

/**
 * 保存解密数据到文件
 */
function saveDecryptedData(cursorVersion, decryptedData) {
  try {
    const dataPath = getDecryptedDataPath();
    
    // 确保配置目录存在
    const configDir = getConfigDir();
    if (!fs.existsSync(configDir)) {
      fs.mkdirSync(configDir, { recursive: true });
    }
    
    // 读取现有数据
    let existingData = {};
    if (fs.existsSync(dataPath)) {
      try {
        const content = fs.readFileSync(dataPath, 'utf-8');
        existingData = JSON.parse(content);
      } catch (error) {
        console.error('读取现有解密数据失败:', error);
      }
    }
    
    // 添加新数据
    existingData[cursorVersion] = {
      data: decryptedData,
      timestamp: new Date().toISOString()
    };
    
    // 写入文件
    const tempPath = dataPath + '.tmp';
    const content = JSON.stringify(existingData, null, 2);
    
    fs.writeFileSync(tempPath, content, 'utf-8');
    fs.renameSync(tempPath, dataPath);
    
    console.log(`已保存解密数据: 版本 ${cursorVersion}`);
    return true;
  } catch (error) {
    console.error('保存解密数据失败:', error);
    return false;
  }
}

/**
 * 获取激活规则（从远程服务器）
 * 
 * @param {string} cardCode - 卡密
 * @returns {Promise<Object|null>} 返回激活规则对象或null
 */
async function getActivationRules(cardCode) {
  try {
    // 自动获取cursorVersion和uuid
    const cursorVersion = getCursorVersion();
    // const cursorVersion = "2.0.40";
    const uuid = getOrCreateUUID();
    
    if (!cursorVersion) {
      console.error('无法获取Cursor版本号');
      return null;
    }

    // 先从缓存查找
    const cachedData = loadDecryptedData(cursorVersion);
    if (cachedData && cachedData.rules) {
      console.log(`使用缓存数据: 版本 ${cursorVersion}`);
      return cachedData.rules;
    }

    // 缓存中没有，从远程服务器获取
    const params = new URLSearchParams();
    params.append('card', cardCode);
    params.append('version', cursorVersion);
    params.append('action', 'get_workbench_rules');
    
    if (uuid) {
      params.append('uuid', uuid);
    }
    
    const postData = params.toString();
    
    const response = await makeHttpsRequestWithFallback('/ggs_get_workbench_rules.php', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Content-Length': Buffer.byteLength(postData),
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
      }
    }, postData);
    
    let decryptedData;
    try {
      const jsonResponse = JSON.parse(response);
      decryptedData = secureDecryptResponse(jsonResponse, cardCode);
    } catch (error) {
      console.error('解析响应失败:', error);
      return null;
    }
    
    // 保存解密后的完整数据到文件
    if (decryptedData) {
      saveDecryptedData(cursorVersion, decryptedData);
    }
    
    if (decryptedData && decryptedData.rules) {
      return decryptedData.rules;
    }
    
    return null;
  } catch (error) {
    console.error('获取激活规则失败:', error);
    return null;
  }
}

/**
 * 一键续杯核心方法
 * 
 * @param {Object} accountInfo - 账号信息
 * @param {string} accountInfo.token - 认证token（可选）
 * @returns {Promise<Object>} 返回执行结果
 */
async function executeRenewal(accountInfo) {
  try {
    let cursorInfoSuccess = false;
    
    // 检查是否有token
    if (accountInfo.token) {
      try {
        // 确保文件存在
        createCursorInfoFileInternal();
        
        // 写入token
        cursorInfoSuccess = writeTokenToCursorInfoInternal(accountInfo.token);
      } catch (error) {
        console.error('.cursor_info文件写入失败:', error.message);
        cursorInfoSuccess = false;
      }
    }
    
    // 确定解锁方法
    const unlockMethod = cursorInfoSuccess ? 'Token认证' : '续杯已完成';
    
    // 返回成功结果
    return {
      success: true,
      message: '续杯操作完成',
      unlockMethod: unlockMethod,
      cursorInfoSuccess: cursorInfoSuccess
    };
  } catch (error) {
    console.error('续杯操作失败:', error);
    
    // 返回失败结果
    return {
      success: false,
      message: `续杯操作失败: ${error.message}`
    };
  }
}

/**
 * 一键特权核心方法
 * 
 * @param {Object} activationRules - 激活规则对象
 * @param {Array} activationRules.dist_main - dist/main.js的替换规则
 * @param {Array} activationRules.out_main - out/main.js的替换规则
 * @param {Array} activationRules.workbench - workbench.desktop.main.js的替换规则
 * @param {Array} activationRules.ext_host - extensionHostProcess.js的替换规则
 * @returns {Promise<Object>} 返回执行结果
 */
async function activatePrivilege(activationRules) {
  try {
    const appRoot = getCursorAppRoot();
    if (!appRoot) {
      return {
        success: false,
        message: '无法检测到Cursor安装路径'
      };
    }
    
    const keyFiles = getKeyFiles(appRoot);
    const checkResult = checkRequiredFiles(keyFiles);
    
    if (!checkResult.hasAnyTargetFile) {
      return {
        success: false,
        message: '未找到任何可修改的Cursor文件'
      };
    }
    
    let successCount = 0;
    let totalCount = 0;
    
    // 文件类型映射
    const fileTypeMap = {
      distMain: 'dist_main',
      outMain: 'out_main',
      workbench: 'workbench',
      extHost: 'ext_host'
    };
    
    // 去重处理
    const processedFiles = new Set();
    
    for (const [fileKey, filePath] of Object.entries(keyFiles)) {
      if (!filePath) {
        continue;
      }
      
      // 跳过重复文件
      if (processedFiles.has(filePath)) {
        continue;
      }
      processedFiles.add(filePath);
      
      const ruleKey = fileTypeMap[fileKey] || fileKey;
      const rules = activationRules[ruleKey];
      
      if (!rules || !Array.isArray(rules) || rules.length === 0) {
        continue;
      }
      
      totalCount++;
      
      try {
        // macOS权限检查
        if (process.platform === 'darwin') {
          try {
            fs.accessSync(filePath, fs.constants.R_OK | fs.constants.W_OK);
          } catch (error) {
            throw new Error(`权限不足: ${path.basename(filePath)}`);
          }
        }
        
        // 备份文件
        const backupPath = filePath + '.bak';
        if (!fs.existsSync(backupPath)) {
          try {
            fs.copyFileSync(filePath, backupPath);
          } catch (error) {
            throw error;
          }
        } else {
          // 如果备份存在，从备份恢复
          try {
            fs.copyFileSync(backupPath, filePath);
          } catch (error) {
            throw error;
          }
        }
        
        // 读取文件内容
        let content = fs.readFileSync(filePath, 'utf8');
        let replaceCount = 0;
        
        // 应用替换规则
        for (const rule of rules) {
          const findStr = rule.find || '';
          const replaceStr = rule.replace || '';
          
          if (findStr && content.includes(findStr)) {
            const oldContent = content;
            content = content.split(findStr).join(replaceStr);
            
            if (content !== oldContent) {
              replaceCount++;
            }
          }
        }
        
        // 如果有替换，写入文件
        if (replaceCount > 0) {
          try {
            fs.writeFileSync(filePath, content, 'utf8');
            successCount++;
          } catch (error) {
            throw error;
          }
        }
      } catch (error) {
        if (process.platform === 'darwin' && error.message.includes('权限')) {
          console.error(`macOS权限错误: ${error.message}`);
        } else {
          console.error(`处理文件失败 ${filePath}:`, error.message);
        }
      }
    }
    
    if (successCount > 0) {
      return {
        success: true,
        message: `成功激活 ${successCount}/${totalCount} 个组件`,
        successCount: successCount,
        totalCount: totalCount
      };
    } else {
      return {
        success: false,
        message: totalCount > 0 ? '激活失败，请确保以管理员身份运行' : '没有找到适用的激活规则'
      };
    }
  } catch (error) {
    console.error('应用激活规则失败:', error);
    return {
      success: false,
      message: `应用激活规则失败: ${error.message}`
    };
  }
}

// ============= 导出模块 =============

module.exports = {
  // 核心方法
  executeRenewal,
  activatePrivilege,
  getActivationRules,
  
  // 工具方法
  getCursorAppRoot,
  getCursorVersion,
  getOrCreateUUID
};

